package com.aikon.wht.concurrent;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.Future;
import java.util.concurrent.RecursiveTask;

/**
 * @author haitao.wang
 */
public class CountTask extends RecursiveTask {

    int threshold = 100000;

    int start;

    int end;

    public CountTask(int start, int end) {
        this.start = start;
        this.end = end;
    }

    @Override
    protected Integer compute() {
        int sum = 0;
        if (end - start <= threshold) {
            for (int i = start; i <= end; i++) {
                sum += i;
            }
        } else {
            int mid = (end + start) / 2;
            CountTask task1 = new CountTask(start, mid);
            CountTask task2 = new CountTask(mid + 1, end);
            task1.fork();
            task2.fork();
            int result1 = (int) task1.join();
            int result2 = (int) task2.join();
            sum = result1 + result2;
        }
        return sum;
    }

    public static void main(String[] args) {
        int start = 1;
        int end = 879787;
        new Thread() {
            public void run() {
                ForkJoinPool forkJoinPool = new ForkJoinPool();
                Future future = forkJoinPool.submit(new CountTask(start, end));
                try {
                    System.out.println("b " + future.get());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                }
            }
        }.start();

        new Thread() {
            @Override
            public void run() {
                System.out.println("a " + CountTask.computeSum(start, end));
            }
        }.start();

    }

    public static int computeSum(int start, int end) {
        int sum = 0;
        for (int i = start; i <= end; i++) {
            sum += i;
        }
        return sum;
    }
}
